import edu.ucdavis.genomics.metabolomics.binbase.connector.references.pubchem.PubchemSubstanceSDFResolver
import org.apache.log4j.Logger
import edu.ucdavis.genomics.metabolomics.binbase.connector.references.sdf.*
import edu.ucdavis.genomics.metabolomics.binbase.connector.references.chebi.ChebiContentResolver

//configuration file
def config = new ConfigSlurper().parse(new File('grails-app/conf/PathConfiguration.groovy').toURL())

Logger logger = Logger.getLogger("ImportChebi")

logger.info "import chebi files"
String tempDir = config.files.chebi.rawdata

FileHelper.workOnDir(tempDir, {File file ->
  ChebiFinder sub = new ChebiFinder()
  SdfToInchi.sdfToInchi(new FileInputStream(file), sub)

}, logger, ".sdf")

class ChebiFinder implements InchFinder{
  private int counter = 0

  void foundInchi(String s, Map<Object, Object> objectObjectMap) {
    Logger logger = Logger.getLogger("ImportChebi")


    ChebiContentResolver resolver = new ChebiContentResolver()
    resolver.prepare objectObjectMap

    Compound compound = CompoundHelper.getCompound(resolver.getInchi(),resolver.getInchiKey(),logger)

    List<String> synonyms = resolver.getSynonyms();
    
    CompoundHelper.updateChebiId (Chebi.findAllByCompound(compound),logger,compound,resolver.getId())
    CompoundHelper.addSynonym synonyms,logger,compound
    CompoundHelper.saveCompound compound,logger

    CompoundHelper.aquireStatistic()

    counter++

    logger.debug "import count: " + counter
  }
}